using System;
using System.Collections;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
using System.Security;
using System.Threading;
using System.Net;
using System.IO;
using System.Security.Principal;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.MSProject;
using PSLib = Microsoft.Office.Project.Server.Library;

namespace ProjectServerTests
{
    public class ProjectServer2007ProjPro : IDisposable
    {
        private Application app = null;
        private string serverURL = "";
        private wsLogin.LoginWindows login;
        private wsProject.Project project;
        private wsProject.ProjectDataSet dsProjects;
        private ArrayList managerProjectMap = new ArrayList();
        private ArrayList managerList = new ArrayList();
        private ArrayList projectList = new ArrayList();
        private string currentProject;
        private int currentProjectIndex = 0;

        // Make the default constructor private since we are using 
        private ProjectServer2007ProjPro()
        {
        }

        public ProjectServer2007ProjPro(string projectServerURL)
        {
            try
            {
                serverURL = projectServerURL.Trim();

                // If no serve URL then assume it is client only.
                if (serverURL.Length > 0)
                {
                    if (serverURL[serverURL.Length - 1] == '/')
                    {
                        serverURL = serverURL.Substring(0, serverURL.Length - 1);
                    }
                    CookieContainer cookies = new CookieContainer();

                    login = new wsLogin.LoginWindows();
                    login.Url = serverURL + "/_vti_bin/PSI/loginWindows.asmx";
                    login.Credentials = CredentialCache.DefaultCredentials;
                    login.CookieContainer = cookies;

                    if (!login.Login())
                    {
                        throw new System.Exception("Could not login to " + serverURL);
                    }

                    project = new wsProject.Project();
                    project.Url = serverURL + "/_vti_bin/PSI/project.asmx";
                    project.Credentials = CredentialCache.DefaultCredentials;
                    project.CookieContainer = cookies;

                    // Load the data set with a list of projects for this user.
                    dsProjects = project.ReadProjectStatus(Guid.Empty,
                    wsProject.DataStoreEnum.PublishedStore, "", 0);
                    currentProjectIndex = 0;
                }

                if (app == null)
                {
                    string paramList = "";
                    if (serverURL.Length > 0)
                    {
                        paramList = paramList + " /s " + projectServerURL;
                    }
                    Process.Start(GetWinProjectLocation(), paramList);

                    // Wait for Project Server connection to startup
                    if (IsProjectRunning(10000.0))
                    {
                        app = new ApplicationClass();
                        app.Alerts((object)false);
                        app.DisplayAlerts = false;
                        app.AppMinimize();

                        bool connectedToProjectServer = (app.ActiveProject.ServerURL == projectServerURL);
                        app.FileCloseAll(PjSaveType.pjDoNotSave);
                        if (!connectedToProjectServer)
                        {
                            throw ( new System.Exception ( "Project Professional could not connect to Project Server" ) ) ;
                        }
                    }
                    else
                    {
                        throw (new System.Exception("Project Professional failed to startup."));
                    }
                }
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.Constructor", ex.Message, EventLogEntryType.Error);
            }
        }

        public void Dispose()
        {
            try
            {
                if (app != null)
                {
                    app.Quit(PjSaveType.pjDoNotSave);
                    app = null;
                }
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.Dispose", ex.Message, EventLogEntryType.Error);
            }
            finally
            {
                GC.SuppressFinalize(this);
            }
        }

        public long Open(string fileName, bool readOnly)
        {
            try
            {
                long tics = 0;
                if (app != null)
                {
                    // If filename = * then assume win auth and use the project list for this user.
                    if (fileName == "*")
                    {
                        if (currentProjectIndex >= dsProjects.Project.Count)
                        {
                            currentProjectIndex = 0;
                        }
                        currentProject = dsProjects.Project[currentProjectIndex].PROJ_NAME;
                        currentProjectIndex++;
                    }
                    else
                    {
                        // Handle wildcards in the project name to randomize the test.
                        currentProject = ReplaceWildcards(fileName);
                    }
                    if (serverURL.Length > 0)
                    {
                        currentProject = "<>\\" + currentProject;
                    }
                    Stopwatch timePerOp = new Stopwatch();

                    timePerOp.Start();
                    app.FileOpen(currentProject, readOnly, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, PjPoolOpen.pjDoNotOpenPool, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.Open", ex.Message + "\nFileName = " + currentProject, EventLogEntryType.Error);
                return 0;
            }
        }

        public long New(string fileName, bool readOnly)
        {
            string newFileName = fileName;
            try
            {
                long tics = 0;
                if (app != null)
                {
                    // Handle wildcards in the project name to randomize the test.
                    newFileName = ReplaceWildcards(fileName);
                    Stopwatch timePerOp = new Stopwatch();

                    timePerOp.Start();
                    app.FileNew(Missing.Value, Missing.Value, false, Missing.Value);
                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.New", ex.Message + "\nFileName = " + newFileName, EventLogEntryType.Error);
                return 0;
            }
        }

        public long Close()
        {
            try
            {
                long tics = 0;
                if (app != null)
                {
                    Stopwatch timePerOp = new Stopwatch();

                    timePerOp.Start();
                    app.FileClose(PjSaveType.pjSave, false);
                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.Close", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long Save()
        {
            try
            {
                long tics = 0;
                if (app != null)
                {
                    Stopwatch timePerOp = new Stopwatch();

                    timePerOp.Start();
                    app.FileSave();
                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.Save", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long SaveAs(string fileName)
        {
            try
            {
                long tics = 0;
                if (app != null)
                {
                    Stopwatch timePerOp = new Stopwatch();

                    timePerOp.Start();
                    app.FileSaveAs(fileName, PjFileFormat.pjMPP, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.SaveAs", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long Publish(bool republish, string baseURL)
        {
            try
            {
                long tics = 0;
                if (app != null)
                {
                    Stopwatch timePerOp = new Stopwatch();

                    timePerOp.Start();
                    app.Publish(republish, baseURL);  //"http://physical:81/20k/"
                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.Publish", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long CheckIn()
        {
            try
            {
                long tics = 0;
                if (app != null)
                {
                    Stopwatch timePerOp = new Stopwatch();

                    timePerOp.Start();
                    app.CheckIn(true, "", true);
                    //ProjectServer2007PSI psi = new ProjectServer2007PSI(serverURL);
                    //psi.QueueCheckInProject(app.ActiveProject.Name, true);
                    //psi.Dispose();

                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.CheckIn", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long CheckOut()
        {
            try
            {
                long tics = 0;
                if (app != null)
                {
                    Stopwatch timePerOp = new Stopwatch();

                    timePerOp.Start();
                    app.CheckOut();
                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.CheckOut", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long AddTask(string taskName)
        {
            string newTaskName;
            try
            {
                long tics = 0;
                if (app != null)
                {
                    newTaskName = ReplaceWildcards(taskName);
                    Stopwatch timePerOp = new Stopwatch();

                    // Calculate the duration.
                    Random rand = new Random(DateTime.Now.Millisecond);
                    int duration = ((Convert.ToInt32(rand.NextDouble() * 90)) + 30) * 720;

                    timePerOp.Start();
                    Task t = app.ActiveProject.Tasks.Add(newTaskName, Missing.Value);
                    t.Duration = duration;
                    timePerOp.Stop();
                    tics = timePerOp.ElapsedMilliseconds;
                }
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.CheckOut", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public void Wait(long waitTime)
        {
            long tics = 0;
            Stopwatch timePerOp = new Stopwatch();
            timePerOp.Start();
            do
            {
                tics = timePerOp.ElapsedMilliseconds;
            } while (tics < waitTime);
            timePerOp.Stop();
        }

        #region Helper Functions
        private string GetNumber(string userID)
        {
            // Assume that the user ID is in the form of test###.
            string num = userID.Substring(4, userID.Length - 4);
            string prefix = "";
            for (int i = 0; i < 5 - (userID.Length - 4); i++)
            {
                prefix = prefix + '0';
            }
            return prefix + num;
        }

        private void LoadMap()
        {
            string line;
            string manager;
            string project;
            int index;
            using (TextReader streamReader = new StreamReader("c:\\ProjectMap.txt"))
            {
                while (true)
                {
                    line = streamReader.ReadLine();
                    if (line != null)
                    {
                        index = line.IndexOf('\t');
                        manager = line.Substring(0, index);
                        project = line.Substring(index + 1, line.Length - index - 1);
                        managerProjectMap.Add(line);
                        managerList.Add(manager);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        private void FillProjectList(string theManager)
        {
            int index;
            string manager;
            string project;
            foreach (string line in managerProjectMap)
            {
                index = line.IndexOf('\t');
                manager = line.Substring(0, index);
                project = line.Substring(index + 1, line.Length - index - 1);
                if (theManager == manager)
                {
                    projectList.Add(project);
                }
            }
        }

        private string GetWinProjectLocation()
        {
            RegistryKey rk = Registry.ClassesRoot.OpenSubKey("MSProject.MPD\\shell\\Open\\command");
            string location = (string)rk.GetValue("");
            rk.Close();
            return location.Substring(1, location.Length - 7);
        }

        private bool IsProjectRunning(double WaitTime)
        {
            int i;
            DateTime currentTime = DateTime.Now;
            DateTime adjustedTime = currentTime.AddSeconds(WaitTime);
            TimeSpan targetTime = new TimeSpan(adjustedTime.Ticks);

            i = targetTime.CompareTo(new TimeSpan(DateTime.Now.Ticks));

            while (i >= 0)
            {
                int hwdMain = FindWindow("JWinproj-WhimperMainClass", null);
                if (hwdMain > 0)
                {
                    int hwdMDI = FindWindowEx(hwdMain, 0, "MDIClient", null);
                    if (hwdMDI > 0)
                    {
                        // Project Server initialization not complete till project shows in window
                        if (FindWindowEx(hwdMDI, 0, "Winproj-DocWindowClass", null) > 0)
                            // Found Window
                            return true;
                        else
                            Thread.Sleep(200);
                    }
                    else
                        Thread.Sleep(200);
                }
                else
                    Thread.Sleep(200);

                i = targetTime.CompareTo(new TimeSpan(DateTime.Now.Ticks));
            }
            // Failed to get window before wait time expired
            return false;

        }
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string strClassName, string strWindowName);
        [DllImport("User32.dll")]
        private static extern int FindWindowEx(int hwndParent, int hwndChildAfter, string strClassName, string strWindowName);

        private bool GenerateSubKeys()
        {
            try
            {
                RegistryKey regKey;
                // HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\MS Project\Profiles
                regKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Office\\12.0\\", true).OpenSubKey("MS Project", true).CreateSubKey("Profiles");
                regKey.CreateSubKey("P12 Default Profile");
                regKey.Close();

                // HKEY_USERS\.default\Software\Microsoft\Office\12.0
                //regKey = Registry.Users.OpenSubKey(".default\\Software\\Microsoft\\Office\\", true).OpenSubKey("12.0").OpenSubKey("MS Project", true).CreateSubKey("Profiles");
                //regKey.CreateSubKey("P12 Default Profile");
                //regKey.Close();
                return true;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.GenerateSubKeys", ex.Message, EventLogEntryType.Error);
                return false;
            }
        }

        private bool GeneratedRegKeys(string serverName, string userName, bool bCurrentMachine)
        {
            try
            {
                RegistryKey regKey;
                Guid oGuid = new Guid();
                if (bCurrentMachine)
                {
                    regKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Office\\12.0\\", true).OpenSubKey("MS Project", true).OpenSubKey("Profiles", false).OpenSubKey("P12 Default Profile", true);
                }
                else
                {
                    regKey = Registry.Users.OpenSubKey(".default\\Software\\Microsoft\\Office\\12.0\\", true).OpenSubKey("MS Project", true).OpenSubKey("Profiles", false).OpenSubKey("P12 Default Profile", true);
                }
                if (regKey != null)
                {
                    regKey.SetValue("Name", "P12");
                    regKey.SetValue("Path", serverName);
                    regKey.SetValue("AccountType", "0");
                    regKey.SetValue("UserName", ""); //userName);
                    regKey.SetValue("Default", "Yes");
                    regKey.SetValue("GUID", oGuid);
                    regKey.SetValue("EntGlobalLastMod", "P12");
                    regKey.SetValue("ServerAllowsMasterProjects", "Yes");
                    regKey.SetValue("ServerAllowsLocalBaseCals", "No");
                    regKey.SetValue("ServerProtectsActuals", "No");
                    regKey.SetValue("DisableMacros", "No");
                    regKey.SetValue("DisableProjInfoGrid", "No");
                    regKey.SetValue("DisableSaveAsGrid", "No");
                    regKey.SetValue("CachedGlobalCPID", "1252");
                    regKey.SetValue("LastDBBootCPID", "1252");
                    regKey.SetValue("ServerCurrency", "USD");
                    regKey.Close();
                }
                // Set the URL trust.
                regKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ZoneMap\\Domains\\ps2007b2", true);
                if (regKey != null)
                {
                    regKey.SetValue("Http", 2);
                    regKey.Close();
                }
                return true;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007ProjPro.GenerateSubKeys", ex.Message, EventLogEntryType.Error);
                return false;
            }
        }

        // Replaces any ? characters in the string with digits 0 - 9 to randomize
        // file names.  It is assumed that projects have been populated to cover the 
        // namespace generated by the wildcard.
        private string ReplaceWildcards(string fileName)
        {
            string newFileName = "";
            if (fileName.Contains("?"))
            {
                Random rand = new Random(DateTime.Now.Millisecond);
                string digit;
                for (int index = 0; index < fileName.Length; index++)
                {
                    if (fileName[index] == '?')
                    {
                        digit = Convert.ToString(rand.NextDouble() * 10);
                        newFileName = newFileName + digit[0];
                    }
                    else
                    {
                        newFileName = newFileName + fileName[index];
                    }
                }
            }
            else
            {
                newFileName = fileName;
            }
            return newFileName;
        }
        #endregion
    }

/*
    public class ProjectServer2007PSI : IDisposable
    {
        private loginWS.LoginWindows login;
        private projectWS.Project project;
        private queueWS.QueueSystem queue;

        private ProjectServer2007PSI()
        {
        }

        public ProjectServer2007PSI(string serverURL)
        {
            try
            {
                login = new loginWS.LoginWindows();
                login.Url = serverURL + "/_vti_bin/PSI/loginWindows.asmx";
                login.Credentials = CredentialCache.DefaultCredentials;

                if (!login.Login())
                {
                    throw new System.Exception("Could not login to " + serverURL);
                }

                project = new projectWS.Project();
                project.Url = serverURL + "/_vti_bin/PSI/project.asmx";
                project.Credentials = CredentialCache.DefaultCredentials;

                queue = new queueWS.QueueSystem();
                queue.Url = serverURL + "/_vti_bin/PSI/queuesystem.asmx";
                queue.Credentials = CredentialCache.DefaultCredentials;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.Constructor", ex.Message, EventLogEntryType.Error);
            }
            finally
            {
                GC.SuppressFinalize(this);
            }
        }

        public void Dispose()
        {
            try
            {
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.Dispose", ex.Message, EventLogEntryType.Error);
            }
        }

        public long QueueCheckInProject(string projName, bool forceCheckin)
        {
            try
            {
                long tics;
                Stopwatch timePerOp = new Stopwatch();
                Guid projectGuid = GetProjectUidFromProjectName(projName);
                Guid jobGuid = Guid.NewGuid();
                Guid sessionGuid = Guid.NewGuid();

                timePerOp.Start();

                project.QueueCheckInProject(jobGuid, projectGuid, forceCheckin, sessionGuid, "");
                WaitForQueueJobCompletion(jobGuid, 11);

                timePerOp.Stop();
                tics = timePerOp.ElapsedMilliseconds;
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.ReadFilteredProjectList", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long ReadFilteredProjectList(string filter)
        {
            try
            {
                long tics;
                Stopwatch timePerOp = new Stopwatch();

                timePerOp.Start();
                timePerOp.Stop();
                tics = timePerOp.ElapsedMilliseconds;
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.ReadFilteredProjectList", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long ReadProjectList()
        {
            try
            {
                long tics = 0;
                Stopwatch timePerOp = new Stopwatch();

                timePerOp.Start();
                timePerOp.Stop();
                tics = timePerOp.ElapsedMilliseconds;
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.ReadProjectList", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long ReadResourceAssignments(string filter)
        {
            try
            {
                long tics = 0;
                Stopwatch timePerOp = new Stopwatch();

                timePerOp.Start();
                timePerOp.Stop();
                tics = timePerOp.ElapsedMilliseconds;
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.ReadResourceAssignments", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long ReadProjectStatus()
        {
            try
            {
                long tics = 0;
                Stopwatch timePerOp = new Stopwatch();

                timePerOp.Start();
                timePerOp.Stop();
                tics = timePerOp.ElapsedMilliseconds;
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.ReadProjectStatus", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long SetAssignmentWorkData(string changeXML)
        {
            try
            {
                long tics = 0;
                Stopwatch timePerOp = new Stopwatch();

                timePerOp.Start();
                timePerOp.Stop();
                tics = timePerOp.ElapsedMilliseconds;
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.SetAssignmentWorkData", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long QueueUpdateTimesheet()
        {
            try
            {
                long tics = 0;
                Stopwatch timePerOp = new Stopwatch();

                timePerOp.Start();
                timePerOp.Stop();
                tics = timePerOp.ElapsedMilliseconds;
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.QueueUpdateTimesheet", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        public long SubmitStatus()
        {
            try
            {
                long tics = 0;
                Stopwatch timePerOp = new Stopwatch();

                timePerOp.Start();
                timePerOp.Stop();
                tics = timePerOp.ElapsedMilliseconds;
                return tics;
            }
            catch (System.Exception ex)
            {
                EventLog.WriteEntry("ProjectServerTests.ProjectServer2007PSI.SubmitStatus", ex.Message, EventLogEntryType.Error);
                return 0;
            }
        }

        #region Helper Functions
        public bool WaitForQueueJobCompletion(Guid jobGuid, int messageType)
        {
            queueWS.QueueStatusDataSet queueStatusDataSet = new queueWS.QueueStatusDataSet();
            queueWS.QueueStatusRequestDataSet queueStatusRequestDataSet = new queueWS.QueueStatusRequestDataSet();

            queueWS.QueueStatusRequestDataSet.StatusRequestRow statusRequestRow =
                queueStatusRequestDataSet.StatusRequest.NewStatusRequestRow();
            statusRequestRow.JobGUID = jobGuid;
            statusRequestRow.JobGroupGUID = Guid.NewGuid();
            statusRequestRow.MessageType = -1; //BUGBUG - Rightnow lets just use -1
            queueStatusRequestDataSet.StatusRequest.AddStatusRequestRow(statusRequestRow);

            bool inProcess = true;
            DateTime startTime = DateTime.Now;
            int successState = (int)PSLib.QueueConstants.JobState.Success;
            int failedState = (int)PSLib.QueueConstants.JobState.Failed;
            int blockedState = (int)PSLib.QueueConstants.JobState.CorrelationBlocked;
            while (inProcess)
            {
                queueStatusDataSet = queue.ReadJobStatus(queueStatusRequestDataSet, false,
                    queueWS.SortColumn.Undefined, queueWS.SortOrder.Undefined);

                foreach (queueWS.QueueStatusDataSet.StatusRow statusRow in queueStatusDataSet.Status)
                {
                    if ((statusRow["ErrorInfo"] != System.DBNull.Value
                        && checkStatusRowHasError(statusRow["ErrorInfo"].ToString()) == true)
                        || statusRow.JobCompletionState == blockedState
                        || statusRow.JobCompletionState == failedState)
                    {
                        inProcess = false;
                        return false;
                    }
                    if (statusRow.JobCompletionState == successState)
                    {
                        inProcess = false;
                        return true;
                    }
                    else
                    {
                        inProcess = true;
                        System.Threading.Thread.Sleep(500);
                    }
                }
                DateTime endTime = DateTime.Now;
                TimeSpan span = endTime.Subtract(startTime);
                if (span.Seconds > 20) //Wait for only 20 secs - and then bail out.
                {
                    return false;
                }
            }
            return true;
        }


        public bool checkStatusRowHasError(string errorInfo)
        {
            XmlTextReader xReader = new XmlTextReader(new System.IO.StringReader(errorInfo));
            while (xReader.Read())
            {
                if (xReader.Name == "errinfo" && xReader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    xReader.Read();
                    if (xReader.Value == "")
                        return false;
                    else
                        return true;
                }
            }
            return false;
        }

        private Guid GetProjectUidFromProjectName(string projName)
        {
            // Find the projectUid from the project name.
            projectWS.ProjectDataSet ds;
            ds = project.ReadProjectList();
            Guid projUid = Guid.Empty;
            for (int row = 0; row < ds.Project.Count; row++)
            {
                if (projName == ds.Project[row].PROJ_NAME.ToString())
                {
                    projUid = ds.Project[row].PROJ_UID;
                    break;
                }
            }
            if (projUid == Guid.Empty)
            {
                throw new System.Exception("The project " + projName + " was not found.");
            }
            return projUid;
        }
        #endregion
    }
 */
}
